package sk.pack;

import sk.pack.util.AlertUtil;
import sk.pack.db.BlogConfigDBAdapter;
import sk.pack.db.SpannableBufferHelper;
import sk.pack.BlogConfigConstants;
import sk.pack.BlogInterface;
import sk.pack.BlogInterfaceFactory;
import sk.pack.db.BlogEntryBean;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class BlogPostEditor extends Activity {
	// private boolean flag=false;
	private static final String TAG = "BlogPostEditor";
	EditText bSubject, bBody;
	private static Button button;
	private static BlogEntryBean b = null;
	private ProgressDialog publishProgress = null;
	private final String MSG_KEY = "value";
	int publishStatus = 0;
	private BlogConfigDBAdapter mDbHelper;
	String login = " ", password = " ";

	protected Dialog onCreateDialog(int id) {
		return new AlertDialog.Builder(BlogPostEditor.this).setIcon(
				R.drawable.alert_dialog_icon).setTitle(
				R.string.alert_dialog_two_buttons_title).setPositiveButton(
				R.string.ok, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						bSubject.setText("");
						bBody.setText("");
						/* User clicked OK so do some stuff */
					}
				}).setNegativeButton(R.string.cancel,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {

						/* User clicked Cancel so do some stuff */
					}
				}).create();
	}

	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.editor);
		TextView tv;
		tv = (TextView) findViewById(R.id.edit_tv_post);
		tv.setText(R.string.post);
		tv = (TextView) findViewById(R.id.edit_tv_subject);
		tv.setText(R.string.subject);
		button = (Button) findViewById(sk.pack.R.id.edit_bt_post);
		button.setText(sk.pack.R.string.post);
		bBody = (EditText) findViewById(sk.pack.R.id.edit_et_post);
		bSubject = (EditText) findViewById(sk.pack.R.id.edit_et_subject);
		b = new BlogEntryBean();
		mDbHelper = new BlogConfigDBAdapter(this);
		try {
			mDbHelper.open();
		} catch (Exception e) {
			Log.d(TAG, "Cannot open DB");
		}
		readDB();
		button.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				b.setTitle(bSubject.getText().toString());
				CharSequence cs = (CharSequence) bBody.getText().toString();
				b.setBlogEntry(cs);
				if (!cs.equals("")) {
					post();
				} else {
					AlertUtil.showAlert(BlogPostEditor.this,
							getString(R.string.unable_to_publish),
							getString(R.string.fill_the_post_field));
				}
			}
		});
		button = (Button) findViewById(sk.pack.R.id.edit_bt_clear);
		button.setText(sk.pack.R.string.clear);
		button.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				/**/
				showDialog(0);
			}
		});
	}

	final Runnable mPublishResults = new Runnable() {
		public void run() {
			showPublishedStatus();
		}
	};

	private void showPublishedStatus() {
		publishProgress.dismiss();
		if (publishStatus == 5) {
			AlertUtil.showAlert(this, getString(R.string.publish_status),
					getString(R.string.publish_ok));
			bSubject.setText("");
			bBody.setText("");
			// activity should finish after ok.
		} else {
			String str = "";
			if (publishStatus == 4)
				str = '\n' + getString(R.string.code_4);
			AlertUtil.showAlert(this, getString(R.string.publish_status),
					getString(R.string.publish_failed) + " (Code "
							+ publishStatus + ")" + str);
		}
	}

	private void post() {
		final Activity thread_parent = this;
		publishProgress = ProgressDialog.show(this,
				getString(R.string.publishing_blog_entry),
				getString(R.string.starting_to_publish_blog_entry));
		Thread publish = new Thread() {
			public void run() {
				Bundle status = new Bundle();
				mHandler.getLooper().prepare();
				Message statusMsg = mHandler.obtainMessage();
				publishStatus = 0;
				status.putString(MSG_KEY, "1");
				statusMsg.setData(status);
				mHandler.sendMessage(statusMsg);
				boolean publishOk = false;
				BlogConfigConstants.BlogInterfaceType typeEnum = BlogConfigConstants
						.getInterfaceTypeByNumber(6);
				BlogInterface blogapi = null;
				blogapi = BlogInterfaceFactory.getInstance(typeEnum);
				Log.d(TAG, "Using interface type: " + typeEnum);
				CharSequence config = "";
				blogapi.setInstanceConfig(config);

				status.putString(MSG_KEY, "2");
				statusMsg = mHandler.obtainMessage();
				statusMsg.setData(status);
				mHandler.sendMessage(statusMsg);
				String auth_id = blogapi.getAuthId(login, password);
				publishStatus = 1;
				Log.d(TAG, "Got auth token:" + auth_id);
				publishStatus = 2;
				if (auth_id != null) {
					status.putString(MSG_KEY, "3");
					statusMsg = mHandler.obtainMessage();
					statusMsg.setData(status);
					mHandler.sendMessage(statusMsg);
					String postUri = blogapi.getPostUrl(auth_id);
					SpannableBufferHelper helper = new SpannableBufferHelper();
					status.putString(MSG_KEY, "4");
					statusMsg = mHandler.obtainMessage();
					statusMsg.setData(status);
					mHandler.sendMessage(statusMsg);
					CharSequence cs = b.getBlogEntry();
					EditText et = new EditText(thread_parent);
					et.setText(cs);
					Spannable spa = et.getText();
					spa.setSpan(cs, 0, 1, 1);
					String spannableToXHTML = null;
					try {
						spannableToXHTML = helper.SpannableToXHTML(spa);
					} catch (Exception e) {
						Log.e(TAG, "snova");
					}

					publishOk = blogapi.createPost(thread_parent, auth_id,
							postUri, null, b.getTitle(), null,
							spannableToXHTML, login, login, b.isDraft());
				} else {
					publishStatus = 3;
				}
				status.putString(MSG_KEY, "5");
				statusMsg = mHandler.obtainMessage();
				statusMsg.setData(status);
				mHandler.sendMessage(statusMsg);
				if (publishOk) {
					Log.d(TAG, "Post published successfully!");
					publishStatus = 5;
					/**/
				} else {
					Log.d(TAG, "Publishing of the post failed!");
					publishStatus = 4;
				}
				mHandler.post(mPublishResults);
			}
		};
		publish.start();
		publishProgress
				.setMessage((CharSequence) getString(R.string.started_publishing));
	}

	final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Bundle content = msg.getData();
			String progressId = content.getString(MSG_KEY);
			if (progressId != null) {
				if (progressId.equals("1")) {
					publishProgress
							.setMessage((CharSequence) getString(R.string.preparing_blog_config));
				} else if (progressId.equals("2")) {
					publishProgress
							.setMessage((CharSequence) getString(R.string.authenticating));
				} else if (progressId.equals("3")) {
					publishProgress
							.setMessage((CharSequence) getString(R.string.contacting_server));
				} else if (progressId.equals("4")) {
					publishProgress
							.setMessage((CharSequence) getString(R.string.creating_new_entry));
				} else if (progressId.equals("5")) {
					publishProgress
							.setMessage((CharSequence) getString(R.string.done));
				}
			} else {
				// panic!
			}
		}
	};

	public void readDB() {

		try {
			Cursor bc = mDbHelper.fetchConfig(ProfileManager.FIRST_ROW);
			startManagingCursor(bc);
			login = bc.getString(bc
					.getColumnIndexOrThrow(BlogConfigDBAdapter.KEY_LOGIN));
			password = bc.getString(bc
					.getColumnIndexOrThrow(BlogConfigDBAdapter.KEY_PASSWORD));
			int i = login.length();
			int j = password.length();
			if ((i < 1) || (j < 1)) {
				Log.e(TAG, "There is a bad blog config in DB");
			}
		} catch (Exception e) {
			Log.e(TAG, "Unable to read DB");
		}
		try {
			Cursor bc = mDbHelper.fetchConfig(ProfileManager.SECOND_ROW);
			startManagingCursor(bc);
			bSubject.setText(bc.getString(bc
					.getColumnIndexOrThrow(BlogConfigDBAdapter.KEY_LOGIN)));
			bBody.setText(bc.getString(bc
					.getColumnIndexOrThrow(BlogConfigDBAdapter.KEY_PASSWORD)));
		} catch (Exception e) {
			Log.e(TAG, "Unable to read DB");
		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if (!mDbHelper.updateConfig(ProfileManager.SECOND_ROW, bSubject
				.getText().toString(), bBody.getText().toString())) {
			mDbHelper.createConfig(bSubject.getText().toString(), bBody
					.getText().toString());
		}

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		readDB();
	}
}
